package com.yqb.study.common.webscoket;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@ServerEndpoint("/webSocket/{phone}/{token}")
@Slf4j
public class WebSocket {
	// 注意是javax.websocket.Session
	private Session session;

	private static ConcurrentHashMap<String, WebSocket> webSocketSet = new ConcurrentHashMap<>();

	@OnOpen
	public void onOpen(@PathParam("phone") String phone, @PathParam("token") String token, Session session) {
		this.session = session;

		String key = phone + "_" + token;
		if (webSocketSet.containsKey(key)) {
			return ;
		}
		webSocketSet.put(key, this);
		log.info("【websocket消息】有来自{}新的连接, 总数:{}", key, webSocketSet.size());
	}

	@OnClose
	public void onClose(@PathParam("phone") String phone, @PathParam("token") String token) {
		String key = phone + "_" + token;
		if (webSocketSet.containsKey(key)) {
			webSocketSet.remove(key);			
			log.info("【websocket消息】断开与{}的连接, 总数:{}", key, webSocketSet.size());
		}		
	}

	@OnMessage
	public void onMessage(@PathParam("phone") String phone, @PathParam("token") String token, String message) {
		String key = phone + "_" + token;
		log.info("【websocket消息】收到客户端{}发来的消息:{}", key, message);
	}

	public void sendMessage(String phone, String token, String message) {
		String key = phone + "_" + token;
		if (!webSocketSet.containsKey(key)) {
			return ;
		}
		
		WebSocket webSocket = webSocketSet.get(key);
		log.info("【websocket消息】向{}发送消息, message={}", key, message);
		try {
			webSocket.session.getBasicRemote().sendText(message);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	
	public void closeConnect(String phone, String token) {
		String key = phone + "_" + token;
		if (!webSocketSet.containsKey(key)) {
			return ;
		}
		
		WebSocket webSocket = webSocketSet.get(key);
		try {
			webSocket.session.close();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		webSocket.onClose(phone, token);
	}
}
